<template>
  <div class="app-container">
    <div class="customContainer">
      <el-form :inline="true">
        <el-form-item>
          <span style="margin-right:10px">调出门店：{{this.store_name_out}}</span>
          <dj-gift-search-select @change="searchTextChanged" @keyupEnter="searchClick" />
          <div class="el-button--small el-button el-button el-button--primary" @click="searchClick"> <span>筛选</span></div>
          <div class="el-button--small el-button el-button el-button--primary" @click="getCar"> <span>刷新</span></div>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="carList" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="序号" width="70" type="index"></el-table-column>
        <el-table-column align="center" label="图片" prop="gift_id" width="80">
          <template slot-scope="scope">
            <div style="position:relative">
              <div class="images" :class="[scope.row.ratio<1?'h':'w']"><img :src="scope.row.thumb" /></div>
              <div v-show="scope.row.is_on_sale==0" style="position:absolute;top:0px;left:0px">
                <img src="../../assets/images/yixiajia.png" width="60px">
              </div>
              <viewer style="position:absolute;top:0px;left:0px；z-index:10" class="images"
                :class="[scope.row.ratio<1?'h':'w',scope.row.is_on_sale==0?'off_sale':'']">
                <img :src="scope.row.thumb" :data-source="scope.row.img" class="image" :key="scope.row.thumb" :alt="scope.row.img.split('?image=').pop()">
              </viewer>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="gift_id" @click="gift_other_information = true">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
        <el-table-column align="center" label="神采编号" prop="no_obsolete"></el-table-column>
        <el-table-column align="center" label="国标码" prop="gb_code"></el-table-column>
        <el-table-column align="center" label="成本价（元）" prop="money_cost">
          <template slot-scope="scope"><span>{{scope.row.money_cost|keepTwoNum}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="剩余库存（个）" prop="num"></el-table-column>
        <el-table-column align="center" label="箱规（个/箱）" prop="box_num">
        </el-table-column>
        <el-table-column align="center" label="数量（个）">
          <template slot-scope="scope">
            <!-- <el-input-number v-model="purchase_number" :min="0" :max="(giftItem.num*1-giftItem.car_num)>999999?999999:(giftItem.num-giftItem.car_num)">
            </el-input-number> -->
            <el-input onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" v-model="scope.row.gift_num"
              placeholder="数量" :disabled="!scope.row.isEdit" @change="numberChange(scope.$index)" style="text-align:center"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额小计（元）">
          <template slot-scope="scope">
            <span>{{scope.row.gift_num*scope.row.money_cost|keepTwoNum}} </span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="备注" width="240">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :maxlength="24"></el-input>
          </template>
        </el-table-column> -->
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="160">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isEdit" plain @click="onEditSaveCancel(1,scope)" type="primary" size="mini" style="margin:auto">编辑</el-button>
            <el-button v-if="scope.row.isEdit" plain @click="onEditSaveCancel(2,scope)" type="primary" size="mini" style="margin:auto">保存</el-button>
            <el-button v-if="scope.row.isEdit" plain @click="onEditSaveCancel(3,scope)" type="info" size="mini" style="margin:auto">取消</el-button>
            <el-button v-if="!scope.row.isEdit" plain @click="delClick(scope)" type="danger" size="mini">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box" style="margin:0 14px">
      <el-button type="text" size="small" @click="delCarListClick()">清空购物车</el-button>
      <el-button class="pull-right" size="small" type="primary" :loading="btnLoding" @click="receiving()">提交订单</el-button>
      <p class="pull-right" style="line-height:0">
        种类合计：{{carList.length}}种 数量合计：{{totalOrder}}个 金额合计(不含运费)：{{totalPrice|keepTwoNum}}元
      </p>
    </div>
    <!-- 提交订单弹出窗口 -->
    <el-dialog :visible.sync="receiving_information" width="1100px" title="收货信息" @close="onCommitDialogClose">
      <!-- 收货信息 -->
      <el-row>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">调出门店：</span>
            <span style="width:70%;font-size:14px">{{this.store_name_out}}</span>
          </div>
        </el-col>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">收货门店：</span>
            <el-select style="width:70%;" placeholder="选择择门店" v-model="saveForm.store_id_in" filterable @change="storeChange">
              <el-option v-for="item in store_List" :key="item.store_id" :label="item.name" :value="item.store_id"></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span=10>
          <div class="row-block">
            <!-- <span style="width:30%;text-align:right;font-size:14px">收货仓：</span> -->
            <!-- <span style="width:70%;font-size:14px">{{this.house_name_in}}</span> -->
            <!-- <el-select style="width:70%;" v-model="saveForm.house_id_in" filterable>
              <el-option v-for="item in house_List" :key="item.house_id" :label="item.house_name" :value="item.house_id"></el-option>
            </el-select> -->
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">收货人：</span>
            <el-input style="width:70%;font-size:14px" placeholder="请输入姓名" v-model="saveForm.name"></el-input>
          </div>
        </el-col>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">电话：</span>
            <el-input style="width:70%;" placeholder="请输入手机号码" v-model="saveForm.phone"></el-input>
          </div>
        </el-col>
        <el-col :span=10>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">地区：</span>
            <div style="width:70%;">
              <keep-alive>
                <dj-region style="width:100%;font-size:14px" :getName="true" :isClear="clearRegion" @provVal="provVal(arguments)" @cityVal="cityVal(arguments)"
                  @areaVal="areaVal(arguments)" ref="region"></dj-region>
              </keep-alive>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">详细地址：</span>
        <el-input style="width:91.25%;font-size:14px" type="textarea" :rows="2" :maxlength="160" placeholder="请输入详细地址" resize="none" v-model="saveForm.address">
        </el-input>
      </div>
      <div class="row-block-full">
        <div style="width:8.75%;text-align:right;font-size:14px">订单信息：</div>
        <p style="width:91.25%;text-align:center;font-size:16px">
          种类合计：{{carList.length}}种 数量合计：{{totalOrder}}个 金额合计(不含运费)：{{totalPrice|keepTwoNum}}元
        </p>
      </div>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">订单备注：</span>
        <div style="width:91.25%;height:100px;font-size:14px">
          <!-- <el-input style="display:inline-block;width:100%;height:50%" type="textarea" :rows="4" placeholder="备注" resize="none" :disabled="true"
            v-model="remarkInfo"></el-input> -->
          <el-input style="display:inline-block;width:100%;height:100%" type="textarea" :rows="4" placeholder="备注" v-model="saveForm.remark" resize="none"
            :maxlength="160"></el-input>
        </div>
      </div>
      <div style="width:100%;position:absolute;right: 30px;bottom: 35px;text-align: right;">
        <el-button @click="receiving_information = false">返回修改</el-button>
        <el-button type="primary" @click="saveClick()">确定提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 获取购物车列表，删除购物车礼品，编辑购物车礼品数量，清空购物车，提交购物车订单
import { getCartList, deleteCart, editCart, clearCart, submitOrder } from '@/api/warehouse/kua_allocate_out.js';
// 获取所有门店，获取门店主仓的收货地址
import { getGXAllStoreList } from '@/api/common/gx_platform.js';
import { integer1to999999 } from '@/utils/validate';

import { DjGiftSearchSelect } from '@/components/gift';
export default {
  components: {
    'dj-gift-search-select': DjGiftSearchSelect
  },
  data() {
    return {
      updateRegion: {}, // 更新子组件region时传值
      clearRegion: false, // 清空子组件region中的值
      carList: [],
      allCarList: [],
      btnLoding: false,
      receiving_information: false,
      gift_other_information: false,
      listLoading: false,
      store_List: [],
      remarkInfo: '', // 购物车单个礼品的备注组合
      store_name_out: '', //调出门店名称，router传入
      // house_name_in: '', //收货仓名称 需手动选择
      saveForm: {
        store_id_out: '', //调出门店，router传入
        store_id_in: '', //收货门店（共享） 需手动选择
        // house_id_in: '', //收货仓 需手动选择
        prov: '', //省id
        city: '', //市id
        dist: '', //区id
        prov_name: '',
        city_name: '',
        dist_name: '',
        name: '', //收货人
        phone: '', //电话
        address: '', // 详细地址
        remark: '', //备注
        order: [] //订单详情:[{"gift_id":"2","order_num":"1","look_money":15840000,"money_cost":15840000}]
      },
      searchObj: {
        name: '',
        gift_id: '',
        no_obsolete: '',
        gb_code: ''
      }
    };
  },

  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.$route.params.routerflag) {
        vm.saveForm.store_id_out = vm.$route.params.store_id;
        vm.store_name_out = vm.$route.params.store_name;
        vm.resetSaveForm();
        vm.getStore();
        vm.getCar();
      }
    });
  },
  methods: {
    onEditSaveCancel(type, scope) {
      if (type == 1) {
        // 点击了编辑按钮
        scope.row.isEdit = true;
        scope.row.pre_eidt_num = scope.row.gift_num;
      } else if (type == 2) {
        let val = {
          store_id: this.saveForm.store_id_out,
          gift_id: scope.row.gift_id,
          num: scope.row.gift_num,
          id: scope.row.id
        };
        editCart(val).then(response => {
          console.log(response, 'zst1121 editCart');
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            scope.row.isEdit = false;
          }
        });
      } else {
        // 点击了取消按钮
        scope.row.isEdit = false;
        scope.row.gift_num = scope.row.pre_eidt_num;
      }
    },
    // 搜索输入框内容发生变化
    searchTextChanged(obj) {
      for (let key in obj) this.searchObj[key] = obj[key];
    },
    numberChange(index) {
      if (this.carList[index].gift_num > 999999) {
        this.carList[index].gift_num = this.carList[index].gift_num.slice(0, 6);
      }
      if (this.carList[index].gift_num * 1 > this.carList[index].num * 1) {
        this.carList[index].gift_num = this.carList[index].num;
      }
    },
    resetSaveForm() {
      this.saveForm.store_id_in = '';
      // this.saveForm.house_id_in = '';
      // this.house_name_in = '';
      this.saveForm.prov = '';
      this.saveForm.prov_name = '';
      this.saveForm.city = '';
      this.saveForm.city_name = '';
      this.saveForm.dist = '';
      this.saveForm.dist_name = '';
      this.saveForm.address = '';
      this.saveForm.name = '';
      this.saveForm.phone = '';
      this.saveForm.remark = '';
      this.clearRegion = true; //重置订单确认弹窗中的地区
    },
    onCommitDialogClose() {
      this.clearRegion = false; //取消重置订单确认弹窗中的地区
    },
    // 购物车点提交，校验购物车数据
    receiving() {
      if (this.allCarList.length == 0) {
        this.$message.error('购物车没有商品');
        return;
      }
      for (var i = 0; i < this.allCarList.length; i++) {
        if (this.allCarList[i].isEdit) {
          this.$message.error('修改未保存，请先保存再提交');
          return;
        }
        if (this.allCarList[i].is_on_sale == 0) {
          this.$message.error('购物车中存在已下架商品，请先移除再提交');
          return;
        }
        if (!integer1to999999(this.allCarList[i].gift_num)) {
          this.$message.error('请将数量填写完整,并且数量只能为1-999999的整数!');
          return;
        }
        if (this.allCarList[i].gift_num * 1 > this.allCarList[i].num * 1) {
          this.$message.error('数量不能大于剩余库存!');
          return;
        }
      }
      // let remark = '';
      // for (var elem of this.allCarList) {
      //   if (elem.remark && elem.remark.trim().length > 0) {
      //     remark += '#' + elem.gift_id + '#' + elem.name + '#' + elem.remark.trim() + ';';
      //   }
      // }
      // this.remarkInfo = remark;
      this.receiving_information = true;
    },
    // 完善收货信息后，确认下单
    saveClick() {
      if (!this.saveForm.store_id_in) {
        this.$message.error('未选择收货门店');
        return;
      }
      if (!this.saveForm.name || !this.saveForm.name.trim()) {
        this.$message.error('收货人未填写');
        return;
      }
      if (!this.saveForm.phone || !this.saveForm.phone.trim()) {
        this.$message.error('手机号未填写');
        return;
      }
      if (!this.saveForm.prov_name || !this.saveForm.city_name) {
        this.$message.error('请选择地区');
        return;
      }
      if (!this.saveForm.address || !this.saveForm.address.trim()) {
        this.$message.error('请填写详细地址');
        return;
      }
      let nameReg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/; //验证姓名正则
      if (!nameReg.test(this.saveForm.name)) {
        this.$message.error('收货人名称不规范');
        return;
      }
      let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!phoneReg.test(this.saveForm.phone)) {
        this.$message.error('电话号码格式不正确');
        return;
      }
      this.saveForm.order = [];
      this.allCarList.forEach(val => {
        let obj = {
          gift_id: val.gift_id,
          order_num: val.gift_num,
          look_money: val.money_cost,
          money_cost: val.money_cost
          // remark: val.remark //暂时去掉
        };
        this.saveForm.order.push(obj);
      });
      submitOrder(this.saveForm).then(res => {
        if (res.code == 1) {
          this.$message.success(res.message);
          this.receiving_information = false;
          this.$store.dispatch('delVisitedViews', { name: 'warehouse/kua_allocate_out_cart' }).then(() => {
            this.$router.push({
              name: 'warehouse/kua_allocate_out_add'
              // params: { routerflag: true }
            });
          });
        }
      });
    },
    getCar() {
      this.listLoading = true;
      this.carList = [];
      getCartList({ store_id: this.saveForm.store_id_out })
        .then(response => {
          // console.log(response, 'zst1121 getCartList');
          if (response && response.length > 0) {
            response.forEach(val => {
              // val.ratio /= 100.0;
              val.remark = '';
              val.money_cost = ((val.money_cost * 1) / 1000000).toFixed(2);
              val.isEdit = false;
              val.pre_eidt_num = val.gift_num;
            });
            this.allCarList = response;
            this.carList = [];
            this.carList.push(...this.allCarList);
          } else {
            this.allCarList = [];
            this.carList = [];
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 清空购物车
    delCarListClick() {
      clearCart({ store_id: this.saveForm.store_id_out }).then(response => {
        console.log(response, 'zst1121 clearCart');
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.carList = [];
          this.allCarList = [];
        }
      });
    },
    // 删除购物车礼品
    delClick(scope) {
      this.$confirm('确定移除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCart({ store_id: this.saveForm.store_id_out, gift_id: scope.row.gift_id }).then(response => {
          console.log(response, 'zst1121 deleteCart');
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.carList.splice(scope.$index, 1);
            // this.allCarList.splice(index, 1);
            this.removeArray(this.allCarList, scope.row);
          }
        });
      });
    },
    // 删除数组中的某一个对象_arr:数组 _obj:需删除的对象
    removeArray(_arr, _obj) {
      var length = _arr.length;
      for (var i = 0; i < length; i++) {
        if (_arr[i] == _obj) {
          if (i == 0) {
            _arr.shift(); //删除并返回数组的第一个元素
            return _arr;
          } else if (i == length - 1) {
            _arr.pop(); //删除并返回数组的最后一个元素
            return _arr;
          } else {
            _arr.splice(i, 1); //删除下标为i的元素
            return _arr;
          }
        }
      }
    },
    storeChange() {
      this.getHouseAdress();
    },
    // 获取全部门店
    getStore() {
      getGXAllStoreList().then(response => {
        if (response && response.return_code == 1) {
          this.store_List = response.data;
        } else {
          this.store_List = [];
        }
        console.log(response, 'zst1121 getGXAllStoreList');
      });
    },
    // 获取主仓收货地址
    getHouseAdress() {
      // this.saveForm.house_id_in = '';
      // getStoreHouseAdress({ store_id: this.saveForm.store_id_in }).then(response => {
      //   console.log(response, 'zst1121 getStoreHouseAdress');
      //   if (response) {
      //     this.updateRegion = {
      //       prov: response.prov_id,
      //       city: response.city_id,
      //       area: response.dist_id
      //     };
      //     this.saveForm.prov = response.prov_id;
      //     this.saveForm.city = response.city_id;
      //     this.saveForm.dist = response.dist_id;
      //     this.saveForm.prov_name = response.prov_name;
      //     this.saveForm.city_name = response.city_name;
      //     this.saveForm.dist_name = response.dist_name;
      //     this.saveForm.address = response.address;
      //     this.saveForm.name = response.linkman;
      //     this.saveForm.phone = response.phone;
      //     this.saveForm.house_id_in = response.house_id;
      //     this.house_name_in = response.house_name;
      //   }
      // });
    },
    // 子组件传过来的省
    provVal(val) {
      this.saveForm.prov = val[0];
      this.saveForm.prov_name = val[1];
    },
    // 子组件传过来的市
    cityVal(val) {
      this.saveForm.city = val[0];
      this.saveForm.city_name = val[1];
    },
    // 子组件传过来的区
    areaVal(val) {
      this.saveForm.dist = val[0];
      this.saveForm.dist_name = val[1];
    },
    // 筛选按钮
    searchClick() {
      for (let key in this.searchObj) {
        if (this.searchObj[key]) {
          this.searchBy(key);
          return;
        }
      }
      if (this.carList.length != this.allCarList.length) {
        this.carList = [];
        this.carList.push(...this.allCarList);
      }
    },
    searchBy(key) {
      let searchVal = this.searchObj[key];
      if (key == 'name') {
        this.carList = this.allCarList.filter(val => val[key].indexOf(searchVal) >= 0);
      } else {
        this.carList = this.allCarList.filter(val => val[key] == searchVal);
      }
    }
  },
  computed: {
    totalOrder: function() {
      let num = 0;
      this.carList.forEach(val => {
        num = val.gift_num * 1 + num;
      });
      return num;
    },
    totalPrice: function() {
      let total = 0;
      this.carList.forEach(val => {
        total = val.gift_num * val.money_cost + total;
      });
      return total;
    }
  }
};
</script>
<style scoped>
.app-container >>> .el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: hidden;
}
.app-container >>> .el-dialog {
  height: 650px;
}

.app-container >>> .el-dialog input {
  height: 32px !important;
}

.app-container >>> .el-dialog textarea {
  border-radius: unset;
  padding: 10px 15px;
}

.app-container >>> .el-dialog select {
  width: 32.3%;
}

.app-container >>> .el-dialog .el-dialog__body {
  padding: 30px;
}

.row-block {
  width: 100%;
  height: 50%;
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.row-block-full {
  width: 100%;
  height: 100%;
  margin-top: 8px;
  display: flex;
  align-items: center;
}
</style>